/**
 * 美观的弹出层组件
 */
class Modal {
    constructor() {
        this.overlay = null;
        this.currentModal = null;
        this.init();
    }

    init() {
        // 创建弹出层容器
        this.overlay = document.createElement('div');
        this.overlay.className = 'modal-overlay';
        this.overlay.addEventListener('click', (e) => {
            if (e.target === this.overlay) {
                this.hide();
            }
        });
        document.body.appendChild(this.overlay);

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.currentModal) {
                this.hide();
            }
        });
    }

    show(content) {
        this.overlay.innerHTML = content;
        this.overlay.classList.add('show');
        this.currentModal = this.overlay.querySelector('.modal-content') || this.overlay.firstElementChild;
        document.body.style.overflow = 'hidden';
        
        // 确保模态框居中显示
        setTimeout(() => {
            if (this.currentModal) {
                const viewportHeight = window.innerHeight;
                const modalHeight = this.currentModal.offsetHeight;
                
                // 如果模态框高度超过视口高度的90%，添加滚动样式
                if (modalHeight > viewportHeight * 0.9) {
                    this.currentModal.style.maxHeight = (viewportHeight * 0.9) + 'px';
                    this.currentModal.style.overflowY = 'auto';
                }
            }
        }, 10);
    }

    hide() {
        this.overlay.classList.remove('show');
        document.body.style.overflow = '';
        setTimeout(() => {
            this.overlay.innerHTML = '';
            this.currentModal = null;
        }, 300);
    }

    // 成功提示 - 使用模板方式，避免在JS中写HTML
    success(message, title = '成功', callback = null) {
        // 优先使用新的模态框管理器
        if (typeof showSuccessModal !== 'undefined') {
            showSuccessModal(message, callback, title);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const content = `
            <div class="modal-content">
                <div class="modal-success">
                    <div class="icon">
                        <i class="fas fa-check"></i>
                    </div>
                    <div class="title">${title}</div>
                    <div class="message">${message}</div>
                    <button class="button" onclick="modal.hide(); ${callback ? callback + '()' : ''}">
                        确定
                    </button>
                </div>
            </div>
        `;
        this.show(content);
    }

    // 错误提示 - 使用模板方式，避免在JS中写HTML
    error(message, title = '错误', callback = null) {
        // 优先使用新的模态框管理器
        if (typeof showErrorModal !== 'undefined') {
            showErrorModal(message, callback, title);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const content = `
            <div class="modal-content">
                <div class="modal-error">
                    <div class="icon">
                        <i class="fas fa-times"></i>
                    </div>
                    <div class="title">${title}</div>
                    <div class="message">${message}</div>
                    <button class="button" onclick="modal.hide(); ${callback ? callback + '()' : ''}">
                        确定
                    </button>
                </div>
            </div>
        `;
        this.show(content);
    }

    // 确认对话框 - 使用模板方式，避免在JS中写HTML
    confirm(message, title = '确认', onConfirm = null, onCancel = null) {
        // 优先使用新的模态框管理器
        if (typeof showConfirmModal !== 'undefined') {
            showConfirmModal(message, onConfirm, onCancel, title);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const confirmId = 'confirm_' + Date.now();
        const cancelId = 'cancel_' + Date.now();

        // 临时存储回调函数
        window[confirmId] = () => {
            this.hide();
            if (onConfirm) onConfirm();
            delete window[confirmId];
            delete window[cancelId];
        };

        window[cancelId] = () => {
            this.hide();
            if (onCancel) onCancel();
            delete window[confirmId];
            delete window[cancelId];
        };

        const content = `
            <div class="modal-content">
                <div class="modal-confirm">
                    <div class="icon">
                        <i class="fas fa-question"></i>
                    </div>
                    <div class="title">${title}</div>
                    <div class="message">${message}</div>
                    <div class="buttons">
                        <button class="button-cancel" onclick="${cancelId}()">
                            取消
                        </button>
                        <button class="button-confirm" onclick="${confirmId}()">
                            确定
                        </button>
                    </div>
                </div>
            </div>
        `;
        this.show(content);
    }

    // 加载提示 - 使用模板方式，避免在JS中写HTML
    loading(message = '加载中...') {
        // 优先使用新的模态框管理器
        if (typeof showLoadingModal !== 'undefined') {
            showLoadingModal(message);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const content = `
            <div class="modal-content">
                <div class="modal-loading">
                    <div class="spinner"></div>
                    <div class="message">${message}</div>
                </div>
            </div>
        `;
        this.show(content);
    }

    // 信息提示 - 使用模板方式，避免在JS中写HTML
    info(message, title = '提示', callback = null) {
        // 优先使用新的模态框管理器
        if (typeof showInfoModal !== 'undefined') {
            showInfoModal(message, callback, title);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const content = `
            <div class="modal-content">
                <div class="modal-success">
                    <div class="icon" style="background: #3b82f6;">
                        <i class="fas fa-info"></i>
                    </div>
                    <div class="title">${title}</div>
                    <div class="message">${message}</div>
                    <button class="button" onclick="modal.hide(); ${callback ? callback + '()' : ''}">
                        确定
                    </button>
                </div>
            </div>
        `;
        this.show(content);
    }

    // 警告提示 - 使用模板方式，避免在JS中写HTML
    warning(message, title = '警告', callback = null) {
        // 优先使用新的模态框管理器
        if (typeof showWarningModal !== 'undefined') {
            showWarningModal(message, callback, title);
            return;
        }

        // 降级到原有方式（保持兼容性）
        const content = `
            <div class="modal-content">
                <div class="modal-error" style="background: #fef3c7;">
                    <div class="icon" style="background: #f59e0b;">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <div class="title">${title}</div>
                    <div class="message">${message}</div>
                    <button class="button" style="background: #f59e0b;" onclick="modal.hide(); ${callback ? callback + '()' : ''}">
                        确定
                    </button>
                </div>
            </div>
        `;
        this.show(content);
    }
}

// 创建全局实例
const modal = new Modal();

// 兼容旧的alert, confirm函数（只定义未被toast.js定义的函数）
window.showAlert = function(message, title = '提示') {
    modal.info(message, title);
};

// 只有在toast.js未定义时才定义这些函数
if (typeof window.showSuccess === 'undefined') {
    window.showSuccess = function(message, title = '成功') {
        modal.success(message, title);
    };
}

if (typeof window.showError === 'undefined') {
    window.showError = function(message, title = '错误') {
        modal.error(message, title);
    };
}

// 为模态框版本提供别名
window.showModalSuccess = function(message, title = '成功') {
    modal.success(message, title);
};

window.showModalError = function(message, title = '错误') {
    modal.error(message, title);
};

window.showModalConfirm = function(message, onConfirm, onCancel, title = '确认') {
    modal.confirm(message, title, onConfirm, onCancel);
};

// confirm函数优先使用toast.js的版本，如果不存在则使用modal版本
if (typeof window.showConfirm === 'undefined') {
    window.showConfirm = function(message, onConfirm, onCancel, title = '确认') {
        modal.confirm(message, title, onConfirm, onCancel);
    };
}

window.showLoading = function(message = '加载中...') {
    modal.loading(message);
};

window.hideLoading = function() {
    modal.hide();
};

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = Modal;
}
